"""
存储模块

用于处理会话和配置的持久化。
"""

import os
import json
import pickle
from typing import Dict, Any, Optional, Union
from pathlib import Path
from .models import CloudSDKConfig, ProviderConfig


class StorageManager:
    """存储管理器"""
    
    def __init__(self, base_path: str = "storage"):
        """
        初始化存储管理器
        
        Args:
            base_path: 基础路径
        """
        self.base_path = Path(base_path)
        self.config_path = self.base_path / "config.json"
        self.sessions_path = self.base_path / "sessions"
        
        # 确保目录存在
        self.base_path.mkdir(parents=True, exist_ok=True)
        self.sessions_path.mkdir(parents=True, exist_ok=True)
    
    def save_config(self, config: CloudSDKConfig) -> bool:
        """
        保存配置
        
        Args:
            config: 配置对象
            
        Returns:
            bool: 是否保存成功
        """
        try:
            with open(self.config_path, "w", encoding="utf-8") as f:
                json.dump(config.dict(), f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"保存配置失败: {e}")
            return False
    
    def load_config(self) -> Optional[CloudSDKConfig]:
        """
        加载配置
        
        Returns:
            Optional[CloudSDKConfig]: 配置对象，失败返回None
        """
        try:
            if self.config_path.exists():
                with open(self.config_path, "r", encoding="utf-8") as f:
                    data = json.load(f)
                    return CloudSDKConfig(**data)
            else:
                # 返回默认配置
                return CloudSDKConfig()
        except Exception as e:
            print(f"加载配置失败: {e}")
            return CloudSDKConfig()
    
    def save_session(self, provider_type: str, session_data: Dict[str, Any]) -> bool:
        """
        保存会话数据
        
        Args:
            provider_type: 提供者类型
            session_data: 会话数据
            
        Returns:
            bool: 是否保存成功
        """
        try:
            session_file = self.sessions_path / f"{provider_type}.pkl"
            with open(session_file, "wb") as f:
                pickle.dump(session_data, f)
            return True
        except Exception as e:
            print(f"保存会话失败: {e}")
            return False
    
    def load_session(self, provider_type: str) -> Optional[Dict[str, Any]]:
        """
        加载会话数据
        
        Args:
            provider_type: 提供者类型
            
        Returns:
            Optional[Dict[str, Any]]: 会话数据，失败返回None
        """
        try:
            session_file = self.sessions_path / f"{provider_type}.pkl"
            if session_file.exists():
                with open(session_file, "rb") as f:
                    return pickle.load(f)
            return None
        except Exception as e:
            print(f"加载会话失败: {e}")
            return None
    
    def delete_session(self, provider_type: str) -> bool:
        """
        删除会话数据
        
        Args:
            provider_type: 提供者类型
            
        Returns:
            bool: 是否删除成功
        """
        try:
            session_file = self.sessions_path / f"{provider_type}.pkl"
            if session_file.exists():
                session_file.unlink()
            return True
        except Exception as e:
            print(f"删除会话失败: {e}")
            return False
    
    def list_sessions(self) -> list:
        """
        列出所有会话
        
        Returns:
            list: 会话类型列表
        """
        try:
            sessions = []
            for session_file in self.sessions_path.glob("*.pkl"):
                sessions.append(session_file.stem)
            return sessions
        except Exception as e:
            print(f"列出会话失败: {e}")
            return []
    
    def clear_sessions(self) -> bool:
        """
        清除所有会话
        
        Returns:
            bool: 是否清除成功
        """
        try:
            for session_file in self.sessions_path.glob("*.pkl"):
                session_file.unlink()
            return True
        except Exception as e:
            print(f"清除会话失败: {e}")
            return False


class ConfigManager:
    """配置管理器"""
    
    def __init__(self, storage_manager: StorageManager):
        """
        初始化配置管理器
        
        Args:
            storage_manager: 存储管理器
        """
        self.storage = storage_manager
        self._config = self.storage.load_config()
    
    @property
    def config(self) -> CloudSDKConfig:
        """获取配置"""
        if self._config is None:
            self._config = CloudSDKConfig()
        return self._config
    
    def save_config(self) -> bool:
        """保存配置"""
        return self.storage.save_config(self.config)
    
    def add_provider(self, provider_config: ProviderConfig) -> bool:
        """
        添加提供者配置
        
        Args:
            provider_config: 提供者配置
            
        Returns:
            bool: 是否添加成功
        """
        # 检查是否已存在
        for provider in self.config.providers:
            if provider.type == provider_config.type:
                return False
        
        self.config.providers.append(provider_config)
        return self.save_config()
    
    def remove_provider(self, provider_type: str) -> bool:
        """
        移除提供者配置
        
        Args:
            provider_type: 提供者类型
            
        Returns:
            bool: 是否移除成功
        """
        original_count = len(self.config.providers)
        self.config.providers = [
            p for p in self.config.providers if p.type != provider_type
        ]
        
        if len(self.config.providers) < original_count:
            return self.save_config()
        return False
    
    def get_provider(self, provider_type: str) -> Optional[ProviderConfig]:
        """
        获取提供者配置
        
        Args:
            provider_type: 提供者类型
            
        Returns:
            Optional[ProviderConfig]: 提供者配置，不存在返回None
        """
        for provider in self.config.providers:
            if provider.type == provider_type:
                return provider
        return None
    
    def list_providers(self) -> list:
        """
        列出所有提供者
        
        Returns:
            list: 提供者类型列表
        """
        return [p.type for p in self.config.providers]
    
    def update_provider_config(self, provider_type: str, 
                              config: Dict[str, Any]) -> bool:
        """
        更新提供者配置
        
        Args:
            provider_type: 提供者类型
            config: 新配置
            
        Returns:
            bool: 是否更新成功
        """
        for provider in self.config.providers:
            if provider.type == provider_type:
                provider.config.update(config)
                return self.save_config()
        return False
    
    def enable_provider(self, provider_type: str) -> bool:
        """
        启用提供者
        
        Args:
            provider_type: 提供者类型
            
        Returns:
            bool: 是否启用成功
        """
        for provider in self.config.providers:
            if provider.type == provider_type:
                provider.enabled = True
                return self.save_config()
        return False
    
    def disable_provider(self, provider_type: str) -> bool:
        """
        禁用提供者
        
        Args:
            provider_type: 提供者类型
            
        Returns:
            bool: 是否禁用成功
        """
        for provider in self.config.providers:
            if provider.type == provider_type:
                provider.enabled = False
                return self.save_config()
        return False
    
    def set_session_path(self, session_path: str) -> bool:
        """
        设置会话路径
        
        Args:
            session_path: 会话路径
            
        Returns:
            bool: 是否设置成功
        """
        self.config.session_path = session_path
        return self.save_config()
    
    def set_log_level(self, log_level: str) -> bool:
        """
        设置日志级别
        
        Args:
            log_level: 日志级别
            
        Returns:
            bool: 是否设置成功
        """
        self.config.log_level = log_level
        return self.save_config()


class SessionManager:
    """会话管理器"""
    
    def __init__(self, storage_manager: StorageManager):
        """
        初始化会话管理器
        
        Args:
            storage_manager: 存储管理器
        """
        self.storage = storage_manager
    
    def save_session(self, provider_type: str, session_data: Dict[str, Any]) -> bool:
        """
        保存会话
        
        Args:
            provider_type: 提供者类型
            session_data: 会话数据
            
        Returns:
            bool: 是否保存成功
        """
        return self.storage.save_session(provider_type, session_data)
    
    def load_session(self, provider_type: str) -> Optional[Dict[str, Any]]:
        """
        加载会话
        
        Args:
            provider_type: 提供者类型
            
        Returns:
            Optional[Dict[str, Any]]: 会话数据，失败返回None
        """
        return self.storage.load_session(provider_type)
    
    def delete_session(self, provider_type: str) -> bool:
        """
        删除会话
        
        Args:
            provider_type: 提供者类型
            
        Returns:
            bool: 是否删除成功
        """
        return self.storage.delete_session(provider_type)
    
    def list_sessions(self) -> list:
        """
        列出所有会话
        
        Returns:
            list: 会话类型列表
        """
        return self.storage.list_sessions()
    
    def clear_sessions(self) -> bool:
        """
        清除所有会话
        
        Returns:
            bool: 是否清除成功
        """
        return self.storage.clear_sessions()